import axios from 'axios'

// 导入加载条
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'

// 创建 axios 实例对象
const requests = axios.create({
  baseURL: 'http://gmall-h5-api.atguigu.cn',
  timeout: 5000
})

import store from '@/store'

// 请求拦截器
requests.interceptors.request.use((config) => {
  NProgress.start()
  if (store.state.cart.uuId_token) {
    config.headers.userTempId = store.state.cart.uuId_token
  }
  if (localStorage.getItem('token')) {
    config.headers.token = localStorage.getItem('token')
  }
  return config
})

// 请求响应器
requests.interceptors.response.use(
  (res) => {
    NProgress.done()
    return res.data
  },
  (error) => {
    return Promise.reject(new Error('获取数据失败!'))
  }
)

export default requests
